const Database = require('better-sqlite3')
const config = require('../config')
const db = new Database(config.db.path)
const fs = require('fs').promises
const path = require('path')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')

// 修改初始化函数，只初始化数据库用户
async function initUsers() {
    const initUsers = [
        { username: 'zs', password: 'ddd', root_path: path.join(config.storage.path, 'zs') },
        { username: 'ls', password: 'ddd', root_path: path.join(config.storage.path, 'ls') }
    ];

    for (const user of initUsers) {
        try {
            const existingUser = getUser(user.username)
            if (!existingUser) {
                await createUser(user)
            }
            if(existingUser.root_path!==user.root_path){
                await adjustRootPath(user)
            }
        } catch (err) {
            console.error(`初始化用户${user.username}失败:${err}`)
        }
    }
}

async function createUser(user) {
    const salt = await bcrypt.genSalt(10)
    const hash = await bcrypt.hash(user.password, salt)
    db.prepare('insert into users (username,password,root_path) values (?,?,?)').run(user.username, hash, user.root_path)
}

async function adjustRootPath(user){
    db.prepare('update users set root_path = ? where username = ?').run(user.root_path, user.username);
}

function getUser(username) {
    return db.prepare('select * from users where username=?').get(username)
}

// 确保用户目录存在
async function ensureUserDirectory(rootPath) {
    try {
        await fs.mkdir(rootPath, { recursive: true })
        return true
    } catch (err) {
        console.error(`创建用户目录失败:${err}`)
        return false
    }
}

async function login(username, password) {
    try {
        if (!username || !password) {
            return {
                status: 0,
                message: '用户名或密码不能为空'
            }
        }
        const user = getUser(username)
        if (!user || !(await bcrypt.compare(password, user.password))) {
            return {
                status: 0,
                message: '用户名或密码错误'
            }
        }

        // 登录成功后创建用户目录
        const dirCreated = await ensureUserDirectory(user.root_path)
        if (!dirCreated) {
            return {
                status: 0,
                message: '创建用户目录失败'
            }
        }

        const token = jwt.sign(
            { id: user.id, username: user.username },
            config.jwt.secret,
            { expiresIn: config.jwt.expiresIn }
        )
        
        return {
            status: 1,
            message: '登录成功',
            data: {
                token,
                username: user.username,
                remoteDir: user.root_path
            }
        }
    } catch (err) {
        console.error(`登录失败:${err}`)
        return {
            status: 0,
            message: '登录失败'
        }
    }
}

module.exports = {
    initUsers,
    createUser,
    getUser,
    login
}
